import { LoginUser, logout } from '../pages/Login/store/action'
import store from '../store'
import history from '../utils/history'
import { getItem, setItem } from '../utils/storage'
import { Toast } from 'antd-mobile'
import axios from 'axios'
import { TIMEOUT, BASE_URL } from './config'
import { AxiosError } from 'axios'
const request = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = getItem().token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err: AxiosError<{ message: string }>) => {
    return Promise.reject(err)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (config) => {
    return config
  },
  async (err: AxiosError<{ message: string }>) => {
    if (!err.response) {
      Toast.info('网络繁忙，请稍后重试！')
      return Promise.reject(err)
    }
    if (err.response.status === 400) {
      return Promise.reject(err)
    }
    if (err.response.status !== 401) {
      Toast.info(err.response.data.message)
      return Promise.reject(err)
    }
    const { refresh_token } = getItem()
    if (!refresh_token) {
      history.push({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      return Promise.reject(err)
    }
    if (refresh_token) {
      try {
        const res = await axios({
          url: BASE_URL + 'v1_0/authorizations',
          method: 'put',
          headers: {
            Authorization: `Bearer ${refresh_token}`,
          },
        })
        const tokeninfo = {
          token: res.data.data.token,
          refresh_token: refresh_token,
        }
        setItem(tokeninfo)
        // store.dispatch(LoginUser(tokeninfo))
        return request(err.config)
      } catch (err) {
        setItem({})
        store.dispatch(logout())
        history.push({
          pathname: '/login',
          state: {
            from: history.location.pathname,
          },
        })
        return Promise.reject(err)
      }
    }
  }
)
export default request
